import { IWorld } from '../../engine/ecs/common/world.interface';
import { CollisionEventComponent } from '../../engine/ecs/components/collision-event.component';
import { Entity } from '../../engine/ecs/entities/entity';
import { System } from '../../engine/ecs/systems/system';
import { BulletComponent } from '../components/bullet.component';
import { EnemyComponent } from '../components/enemy.component';

export class EnemyCollisionSystem extends System {
  constructor(public readonly player: Entity) {
    super();
  }

  onUpdate(world: IWorld, dt: number) {
    const entities = world.findEntitiesByComponents([EnemyComponent, CollisionEventComponent]);
    for (const entity of entities) {
      const enemyComponent = world.findComponentByEntity(entity, EnemyComponent)!;
      const collisionEventComponent = world.findComponentByEntity(entity, CollisionEventComponent)!;

      const isCollidedWithBullet =
        collisionEventComponent.data.findIndex((data) => {
          return world.findComponentByEntity(data.collidedEntity, BulletComponent);
        }) !== -1;

      if (isCollidedWithBullet && enemyComponent.hit()) {
        world.removeEntity(entity);
      }
    }
  }
}
